import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _omit from "lodash/omit";
import _map from "lodash/map";
import _isFunction from "lodash/isFunction";
import _forEach from "lodash/forEach";
import _findIndex from "lodash/findIndex";
import _filter from "lodash/filter";
import React from 'react';
import { Modal } from 'antd';
import uuid from 'uuid/v4';
import intl from "../../../utils/intl";
import BaseComposeTable from "./BaseComposeTable";
import ComposeForm from "../ComposeForm";
import { getComponentProps } from "../ComposeForm/utils";
import { getDisplayValue, getWidthFromWord } from "../utils";
import Upload from "../../Upload";
/**
 * 获取计算得来的属性(且耗时多)
 * @param {Object} props
 */

function getComputeTableProps(props) {
  var onRowEdit = props.onRowEdit,
      fields = props.fields,
      editable = props.editable,
      addable = props.addable,
      context = props.context,
      removable = props.removable; // let index = 0;
  // columnWith 在 删除模式下 需要 加上 checkbox 的宽度

  var columnsWidth = removable ? 60 : 0;

  var columns = _map(fields, function (field) {
    // const required = field.requiredFlag !== 0;
    var columnWidth = getWidthFromWord({
      word: field.fieldDescription,
      minWidth: 60,
      fontWidth: 12,
      defaultWidth: 100,
      paddingWidth: 36
    });
    columnsWidth += columnWidth;
    var column = {
      dataIndex: field.fieldCode,
      title: field.fieldDescription,
      width: columnWidth
    };

    if (field.componentType === 'Upload') {
      var uploadProps = getComponentProps({
        field: field,
        componentType: 'Upload',
        context: context
      });

      column.render = function (_, record) {
        var attachmentUUID = record[field.fieldCode];
        return attachmentUUID && /*#__PURE__*/React.createElement(Upload, Object.assign({}, uploadProps, {
          viewOnly: true,
          attachmentUUID: attachmentUUID
        }));
      };
    } else if (field.componentType === 'Checkbox' || field.componentType === 'Switch') {
      column.render = function (item) {
        return item === 1 ? intl.get('cpaas.common.status.yes').d('是') : intl.get('cpaas.common.status.no').d('否');
      };
    } else {
      column.render = function (_, record) {
        return getDisplayValue(field, record);
      };
    }

    return column;
  });

  if (editable) {
    columns.unshift({
      title: intl.get('cpaas.common.button.edit').d('编辑'),
      key: 'edit',
      width: 80,
      render: function render(_, record) {
        return /*#__PURE__*/React.createElement("a", {
          onClick: function onClick() {
            onRowEdit(record);
          }
        }, intl.get('cpaas.common.button.edit').d('编辑'));
      }
    });
  } else if (addable) {
    columns.unshift({
      title: intl.get('cpaas.common.button.edit').d('编辑'),
      key: 'edit',
      width: 80,
      render: function render(_, record) {
        if (record.isCreate) {
          return /*#__PURE__*/React.createElement("a", {
            onClick: function onClick() {
              onRowEdit(record);
            }
          }, intl.get('cpaas.common.button.edit').d('编辑'));
        }
      }
    });
  }

  return {
    scroll: {
      x: columnsWidth
    },
    columns: columns
  };
}

var ComposeTableEditModal = /*#__PURE__*/function (_React$PureComponent) {
  _inherits(ComposeTableEditModal, _React$PureComponent);

  var _super = _createSuper(ComposeTableEditModal);

  function ComposeTableEditModal(props) {
    var _this;

    _classCallCheck(this, ComposeTableEditModal);

    _this = _super.call(this, props);
    _this.state = {};
    _this.composeForm = void 0;
    _this.getDataSource = _this.getDataSource.bind(_assertThisInitialized(_this));
    _this.getValidateDataSource = _this.getValidateDataSource.bind(_assertThisInitialized(_this));
    _this.refComposeForm = _this.refComposeForm.bind(_assertThisInitialized(_this));
    _this.handleRowSelectionChange = _this.handleRowSelectionChange.bind(_assertThisInitialized(_this));
    _this.handleRemove = _this.handleRemove.bind(_assertThisInitialized(_this));
    _this.dataSourceRemove = _this.dataSourceRemove.bind(_assertThisInitialized(_this));
    _this.handleAdd = _this.handleAdd.bind(_assertThisInitialized(_this));
    _this.handleRowEdit = _this.handleRowEdit.bind(_assertThisInitialized(_this));
    _this.handleModalOkBtnClick = _this.handleModalOkBtnClick.bind(_assertThisInitialized(_this));
    _this.handleModalCancelBtnClick = _this.handleModalCancelBtnClick.bind(_assertThisInitialized(_this));
    _this.handleAfterModalClose = _this.handleAfterModalClose.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(ComposeTableEditModal, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props = this.props,
          onGetValidateDataSourceHook = _this$props.onGetValidateDataSourceHook,
          onGetDataSourceHook = _this$props.onGetDataSourceHook;

      if (_isFunction(onGetValidateDataSourceHook)) {
        onGetValidateDataSourceHook(this.getValidateDataSource);
      }

      if (_isFunction(onGetDataSourceHook)) {
        onGetDataSourceHook(this.getDataSource);
      }
    }
  }, {
    key: "getDataSource",
    value: function getDataSource() {
      var dataSource = this.state.dataSource;
      return _map(_filter(dataSource, function (r) {
        return r.isCreate || r.isUpdate;
      }), function (r) {
        return _omit(r, ['isCreate', 'isUpdate']);
      });
    }
  }, {
    key: "getValidateDataSource",
    value: function getValidateDataSource() {
      var dataSource = this.state.dataSource;
      var _this$props$rowKey = this.props.rowKey,
          rowKey = _this$props$rowKey === void 0 ? 'id' : _this$props$rowKey;
      return Promise.resolve(_map(_filter(dataSource, function (r) {
        return r.isCreate || r.isUpdate;
      }), function (r) {
        if (r.isCreate) {
          return _omit(r, ['isCreate', 'isUpdate', rowKey]);
        }

        return _omit(r, ['isCreate', 'isUpdate']);
      }));
    }
  }, {
    key: "refComposeForm",
    value: function refComposeForm(composeForm) {
      var refEditComposeForm = this.props.refEditComposeForm;
      this.composeForm = composeForm;

      if (_isFunction(refEditComposeForm)) {
        refEditComposeForm(composeForm);
      }
    } // 删除

    /**
     *
     * @param {Array} selectedRowKeys - 选中记录的rowKey
     * @param {Array} selectedRows - 选中记录
     */

  }, {
    key: "handleRowSelectionChange",
    value: function handleRowSelectionChange(selectedRowKeys, selectedRows) {
      this.setState({
        selectedRowKeys: selectedRowKeys,
        selectedRows: selectedRows
      });
    }
  }, {
    key: "handleRemove",
    value: function handleRemove() {
      var _this$state = this.state,
          dataSource = _this$state.dataSource,
          selectedRowKeys = _this$state.selectedRowKeys;
      var rowKey = this.props.rowKey;
      var removeRows = [];

      _forEach(dataSource, function (r) {
        if (_findIndex(selectedRowKeys, function (rowId) {
          return rowId === r[rowKey];
        }) !== -1) {
          if (!r.isCreate) {
            removeRows.push(r);
          }
        }
      });

      if (removeRows.length > 0) {
        // 调用 父组件 传进来的 方法
        var onRemove = this.props.onRemove;

        if (_isFunction(onRemove)) {
          this.setState({
            removeLoading: true
          });
          onRemove(_map(removeRows, function (row) {
            return row[rowKey];
          }), removeRows, {
            onOk: this.dataSourceRemove
          });
        }
      } else {
        this.dataSourceRemove();
      }
    }
  }, {
    key: "dataSourceRemove",
    value: function dataSourceRemove() {
      var _this$state2 = this.state,
          dataSource = _this$state2.dataSource,
          selectedRowKeys = _this$state2.selectedRowKeys;
      var rowKey = this.props.rowKey;
      var nextDataSource = [];

      _forEach(dataSource, function (r) {
        if (_findIndex(selectedRowKeys, function (rowId) {
          return rowId === r[rowKey];
        }) === -1) {
          nextDataSource.push(r);
        }
      });

      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
        dataSource: nextDataSource,
        removeLoading: false
      });
    } // 编辑

    /**
     * 打开新增模态框
     */

  }, {
    key: "handleAdd",
    value: function handleAdd() {
      this.setState({
        isUpdate: false,
        editRecord: {},
        modalProps: {
          visible: true
        },
        composeFormProps: {
          dataSource: {}
        }
      });
    }
    /**
     * 点击编辑触发
     * @param {Object} record - 编辑的属性
     */

  }, {
    key: "handleRowEdit",
    value: function handleRowEdit(record) {
      this.setState({
        isUpdate: true,
        editRecord: record,
        modalProps: {
          visible: true
        },
        composeFormProps: {
          dataSource: record
        }
      });
    }
    /**
     * 编辑模态框 确认按钮点击
     */

  }, {
    key: "handleModalOkBtnClick",
    value: function handleModalOkBtnClick() {
      var _this2 = this;

      if (this.composeForm) {
        var form = this.composeForm.props.form;
        form.validateFields(function (err, fieldsValue) {
          if (!err) {
            var isUpdate = _this2.state.isUpdate;

            if (isUpdate) {
              _this2.rowUpdate(fieldsValue);
            } else {
              _this2.rowCreate(fieldsValue);
            }
          }
        });
      }
    }
    /**
     * 更新记录
     * @param {Object}} fieldsValue - 编辑的数据
     */

  }, {
    key: "rowUpdate",
    value: function rowUpdate(fieldsValue) {
      var _this$state3 = this.state,
          _this$state3$editReco = _this$state3.editRecord,
          editRecord = _this$state3$editReco === void 0 ? {} : _this$state3$editReco,
          _this$state3$dataSour = _this$state3.dataSource,
          dataSource = _this$state3$dataSour === void 0 ? [] : _this$state3$dataSour;
      this.setState({
        editRecord: null,
        modalProps: {},
        composeFormProps: {},
        dataSource: _map(dataSource, function (r) {
          if (r === editRecord) {
            return _objectSpread(_objectSpread(_objectSpread({}, r), fieldsValue), {}, {
              isUpdate: true
            });
          }

          return r;
        })
      });
    }
    /**
     * 新增记录
     * @param {Object}} fieldsValue - 编辑的数据
     */

  }, {
    key: "rowCreate",
    value: function rowCreate(fieldsValue) {
      var _objectSpread2;

      var _this$state$dataSourc = this.state.dataSource,
          dataSource = _this$state$dataSourc === void 0 ? [] : _this$state$dataSourc;
      var rowKey = this.props.rowKey;
      this.setState({
        editRecord: null,
        modalProps: {},
        composeFormProps: {},
        dataSource: [].concat(_toConsumableArray(dataSource), [_objectSpread(_objectSpread({}, fieldsValue), {}, (_objectSpread2 = {}, _defineProperty(_objectSpread2, rowKey, uuid()), _defineProperty(_objectSpread2, "isCreate", true), _objectSpread2))])
      });
    }
    /**
     * 编辑模态框 取消按钮点击
     */

  }, {
    key: "handleModalCancelBtnClick",
    value: function handleModalCancelBtnClick() {
      this.setState({
        editRecord: null,
        modalProps: {},
        composeFormProps: {}
      });
    }
    /**
     * 编辑模态框 关闭
     */

  }, {
    key: "handleAfterModalClose",
    value: function handleAfterModalClose() {
      if (this.composeForm) {
        var form = this.composeForm.props.form;
        form.resetFields();
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$state4 = this.state,
          _this$state4$modalPro = _this$state4.modalProps,
          modalProps = _this$state4$modalPro === void 0 ? {} : _this$state4$modalPro,
          _this$state4$composeF = _this$state4.composeFormProps,
          composeFormProps = _this$state4$composeF === void 0 ? {} : _this$state4$composeF,
          dataSource = _this$state4.dataSource,
          confirmLoading = _this$state4.confirmLoading,
          removeLoading = _this$state4.removeLoading,
          selectedRowKeys = _this$state4.selectedRowKeys,
          selectedRows = _this$state4.selectedRows;
      var _this$props2 = this.props,
          fields = _this$props2.fields,
          editModalTitle = _this$props2.editModalTitle,
          _this$props2$fieldLab = _this$props2.fieldLabelWidth,
          fieldLabelWidth = _this$props2$fieldLab === void 0 ? 200 : _this$props2$fieldLab,
          organizationId = _this$props2.organizationId,
          context = _this$props2.context,
          loading = _this$props2.loading;
      var composeTableProps = this.props;
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(BaseComposeTable, Object.assign({
        getComputeTableProps: getComputeTableProps
      }, composeTableProps, {
        onRef: this.refComposeTable,
        dataSource: dataSource,
        onRowEdit: this.handleRowEdit,
        onAdd: this.handleAdd,
        onRemove: this.handleRemove,
        onRowSelectionChange: this.handleRowSelectionChange,
        selectedRowKeys: selectedRowKeys,
        selectedRows: selectedRows,
        loading: loading || removeLoading
      })), modalProps.visible && /*#__PURE__*/React.createElement(Modal, Object.assign({}, modalProps, {
        title: editModalTitle,
        onOk: this.handleModalOkBtnClick,
        onCancel: this.handleModalCancelBtnClick,
        wrapClassName: "ant-modal-sidebar-right",
        transitionName: "move-right",
        width: 1000,
        afterClose: this.handleAfterModalClose,
        confirmLoading: confirmLoading
      }), /*#__PURE__*/React.createElement(ComposeForm, Object.assign({}, composeFormProps, {
        context: context,
        organizationId: organizationId,
        fieldLabelWidth: fieldLabelWidth,
        editable: true,
        col: 2,
        fields: fields,
        onRef: this.refComposeForm
      }))));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: // composeForm 的this

    /**
     * 控制半受控属性 dataSource
     * 当 父组件 dataSource 改变时, 使用父组件的 dataSource, 之后都是本组件自己的dataSource
     * @param {Object} nextProps - 接收的属性
     * @param {Object} prevState - 上一个State
     */
    function getDerivedStateFromProps(nextProps, prevState) {
      if (nextProps.dataSource !== prevState.prevDataSource) {
        return {
          dataSource: nextProps.dataSource,
          prevDataSource: nextProps.dataSource
        };
      }

      return null;
    }
  }]);

  return ComposeTableEditModal;
}(React.PureComponent);

export { ComposeTableEditModal as default };